package com.ilop.sthome.utils.greenDao.utils;

import android.content.Context;
import android.text.TextUtils;

import com.aliyun.iot.aep.sdk.apiclient.callback.IoTResponse;
import com.example.xmpic.ui.data.CameraBeanDao;
import com.example.xmpic.ui.utils.CameraDaoUtil;
import com.ilop.sthome.data.bean.VirtualUserBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.data.greenDao.RoomBean;
import com.ilop.sthome.data.greenDao.RoomBeanDao;
import com.example.xmpic.mvp.model.CameraModel;
import com.example.xmpic.mvp.model.CameraModelImpl;
import com.example.common.mvp.onModelCallBack;
import com.ilop.sthome.utils.ConfigureUtil;
import com.ilop.sthome.utils.greenDao.manage.CommonDaoUtils;
import com.ilop.sthome.utils.greenDao.manage.DaoManager;
import com.siterwell.familywellplus.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RoomDaoUtil {

    private volatile static RoomDaoUtil instance = null;
    private CommonDaoUtils<RoomBean> mRoomUtils;
    private RoomBeanDao mRoomDao;

    public static RoomDaoUtil getInstance(){
        if (instance == null){
            synchronized (RoomDaoUtil.class){
                if (instance == null){
                    instance = new RoomDaoUtil();
                }
            }
        }
        return instance;
    }

    public static void setInstance(){
        instance = null;
    }

    private RoomDaoUtil() {
        DaoManager mManager = DaoManager.getInstance();
        mRoomDao= mManager.getDaoSession().getRoomBeanDao();
        mRoomUtils = new CommonDaoUtils(RoomBean.class, mRoomDao);
    }

    public CommonDaoUtils<RoomBean> getRoomDao(){
        return mRoomUtils;
    }


    /**
     * 默认添加10个房间
     * @param context 上下文
     */
    public void insertDefaultRoom(Context context){
        String[] roomName = {context.getString(R.string.default_room), context.getString(R.string.living_room),
                context.getString(R.string.master_bedroom), context.getString(R.string.supine_bedroom),
                context.getString(R.string.study), context.getString(R.string.kitchen),
                context.getString(R.string.toilet), "", "", ""};
        for (int i = 0; i < 10; i++) {
            RoomBean roomBean = new RoomBean();
            roomBean.setRid("0"+i);
            roomBean.setRoom_name(roomName[i]);
            mRoomUtils.insertOrReplace(roomBean);
        }
    }

    /**
     * 获取对应房间
     * @param roomId 房间ID
     * @return bean
     */
    public RoomBean getRoomByRoomId(String roomId){
        return mRoomDao.queryBuilder()
                .where(RoomBeanDao.Properties.Rid.eq(roomId))
                .build()
                .unique();
    }

    /**
     * 获取当前房间指针
     * @param roomId 房间ID
     * @return int
     */
    public int getPositionByRoomId(String roomId){
        List<RoomBean> mList = mRoomUtils.queryAll();
        int mSize = mList.size();
        for (int i = 0; i < mSize; i++) {
            if (mList.get(i).getRid().equals(roomId)){
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取云端房间和摄像头数据
     * @param userList 云端接口数据列表（房间昵称和摄像头共用）
     */
    public void getRoomData(Context mContext, List<VirtualUserBean> userList){
        if (userList!=null && userList.size() > 0) {
            List<String> roomList = new ArrayList<>();
            List<String> cameraList = new ArrayList<>();
            for (VirtualUserBean bean : userList) {
                String userId = bean.getUserId();
                Map<String, String> map = new HashMap<>();
                for (VirtualUserBean.AttrList name : bean.getAttrList()) {
                    map.put(name.getAttrKey(), name.getAttrValue());
                    roomList.add(map.get("employeeID"));
                    cameraList.add(map.get("name"));
                }
                if (map.size() == 2) {
                    updateNickName(userId, map);
                } else if (map.size() == 3){
                    DeviceDaoUtil.getInstance().insertCamera(mContext, userId, map);
                }else {
                    deleteRoom(userId);
                }
            }
            synchronizationRoom(roomList);
            DeviceDaoUtil.getInstance().synCameraData(cameraList);
        }else {
            DeviceDaoUtil.getInstance().deleteAllCamera();
            resetRoomData();
        }
    }

    /**
     * 更新房间昵称
     * @param value
     */
    private void updateNickName(String userId, Map<String, String> value){
        String roomId = value.get("employeeID");
        if (roomId == null){
            deleteRoom(userId);
        }else {
            RoomBean mRoom = getRoomByRoomId(roomId);
            if (mRoom != null) {
                mRoom.setUserId(userId);
                mRoom.setNickname(value.get("extNum"));
                mRoom.setRoom_name(value.get("extNum"));
                mRoomUtils.update(mRoom);
            }
        }
    }

    /**
     * 同步云端房间名称
     */
    private void synchronizationRoom(List<String> dbOpenidList){
        List<String> allOpenidList = findRoomUserId();
        if (dbOpenidList != null && !dbOpenidList.isEmpty()) {
            Map<String, String> dataMap = new HashMap<>();
            for (String id : dbOpenidList) {
                dataMap.put(id, id);
            }
            for (String id : allOpenidList) {
                if (!dataMap.containsKey(id)) {
                    RoomBean roomBean = getRoomByRoomId(id);
                    roomBean.setNickname(null);
                    mRoomUtils.update(roomBean);
                }
            }
        }else {
            //云端有摄像头但是没房间的情况也需要重置
            resetRoomData();
        }
    }

    /**
     * 云端没房间数据重置本地数据
     */
    private void resetRoomData(){
        List<RoomBean> mList = mRoomUtils.queryAll();
        for (int i = 0; i < 10; i++) {
            RoomBean roomBean = mList.get(i);
            roomBean.setNickname(null);
            mRoomUtils.update(roomBean);
        }
    }

    /**
     * 查找不是空房间的房间列表
     * @return 房间列表
     */
    public List<RoomBean> findRoomNotEmpty(){
        return mRoomDao.queryBuilder()
                .where(RoomBeanDao.Properties.Room_name.notEq(""))
                .build()
                .list();
    }

    /**
     * 查找不是空房间的房间列表
     * @return 房间列表
     */
    public List<RoomBean> findRoomNotEmptyAndDefault(){
        return mRoomDao.queryBuilder()
                .where(RoomBeanDao.Properties.Room_name.notEq(""),
                        RoomBeanDao.Properties.Rid.notEq("00"))
                .build()
                .list();
    }

    /**
     * 查找所有房间的名称
     * @return
     */
    public List<String> findRoomName(Context context){
        List<RoomBean> mRoomList = findRoomNotEmptyAndDefault();
        if (mRoomList.size()>0){
            List<String> nameList = new ArrayList<>();
            for (RoomBean room:mRoomList) {
                if (!TextUtils.isEmpty(room.getNickname())){
                    nameList.add(room.getNickname());
                }else if (!TextUtils.isEmpty(room.getRoom_name())){
                    nameList.add(ConfigureUtil.roomName(context, room.getRid()));
                }
            }
            return nameList;
        }else {
            return null;
        }
    }

    /**
     * 查找所有房间的ID
     * @return
     */
    public List<String> findRoomUserId(){
        List<RoomBean> mRoomList = mRoomUtils.queryAll();
        if (mRoomList.size()>0){
            List<String> mList = new ArrayList<>();
            for (RoomBean room:mRoomList) {
                mList.add(room.getRid());
            }
            return mList;
        }else {
            return null;
        }
    }

    /**
     * 通过房间昵称查询是否已经添加
     * @param name 昵称
     * @return RoomBean
     */
    public RoomBean findRoomByRoomName(String name){
        return mRoomDao.queryBuilder()
                .where(RoomBeanDao.Properties.Nickname.eq(name))
                .build()
                .unique();
    }

    /**
     * 查询空房间列表中的第一个进行添加
     * @return roomId
     */
    public String findFirstEmptyRoom(){
        List<RoomBean> roomBean = mRoomDao.queryBuilder()
                .where(RoomBeanDao.Properties.Room_name.eq(""))
                .build()
                .list();
        if (roomBean.size()>0){
            return roomBean.get(0).getRid();
        }else {
            return null;
        }
    }

    /**
     * 获取所有包含设备的房间
     * @return roomList
     */
    public List<RoomBean> findAllRoomList(){
        List<RoomBean> mRoom = mRoomUtils.queryAll();
        List<DeviceInfoBean> mDevice = DeviceDaoUtil.getInstance().findGatewayAndCamera();
        if (mDevice.size()>0) {
            int shareSize = DeviceDaoUtil.getInstance().findShareGatewayNumber();
            if (shareSize > 0) {
                RoomBean roomBean = new RoomBean();
                roomBean.setRid("198");//分享设备
                mRoom.add(roomBean);
            }
            return mRoom;
        }else {
            return null;
        }
    }

    /**
     * 删除云端接口数据
     * @param userId
     */
    public void deleteRoom(String userId){
        CameraModelImpl model = new CameraModel();
        model.toDeleteCamera(userId, new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {

            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}
